var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Cat = mongoose.model('Cat', { name: String });
var multer  = require('multer')
var path=require("path")

/* GET home page. */
router.get('/', function(req, res, next) {
  var kitty = new Cat({ name: 'pangpang' });
  kitty.save(function (err) {
    if (err) {
      console.log(err);
    } else {
      console.log('success');
    }
  });
  res.render('index', { title: 'Express' });
});

//设置参数
var storage = multer.diskStorage({
	//设置存储入径
  destination: function (req, file, cb) {
    cb(null, './uploads')
  },
  //设置文件名和时间搓
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now()+path.extname(file.originalname))
  }
})

//新增
exports.create=function(req,res,next){
	var user = new User(req.body); // 从req.body里获取参数对象，比如{name:'vane',gender:'男',city:'杭州'....}
    //user是表
    user.save()
    .then(data=>{
        res.json(data)
    })  
}

//实例化
var upload = multer({ storage: storage })
var upload=multer({
				storage: storage,
				fileFilter:function(req,file,callback){
					console.log(file)
					var ext=path.extname(file.originalname);
						if(ext!==".png" && ext!==".jpg" && ext!==".gif"){
							return callback(res.end("文件类型不符合"))
						}
						callback(null,true)
				}
		}).single("avatar")
		
		
router.post("/upload",upload,function(req,res,next){		
		console.log(upload)
		upload(req,res,function(err){
			res.end("file uploaded")
		})
})

module.exports = router;
